<script setup lang="ts">
import { computed, ref, watch } from 'vue';

import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

interface TestItem {
  id: string;
  name: string;
  category: string;
  device: string;
  status: 'completed' | 'error' | 'pending' | 'processing';
  result?: string;
  unit?: string;
  reference?: string;
  abnormal?: boolean;
  createTime: string;
  completeTime?: string;
}

interface StatusMessage {
  time: string;
  text: string;
  type: 'error' | 'info' | 'success' | 'warning';
}

interface OperationLog {
  time: string;
  action: string;
  operator: string;
}

interface Props {
  visible: boolean;
  testItem: null | TestItem;
}

interface Emits {
  (e: 'update:visible',visible: boolean): void
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const progressPercent = ref(0);
const progressStatus = ref<'active' | 'exception' | 'success'>('active');
const progressColor = ref('#1890ff');
const statusMessages = ref<StatusMessage[]>([]);
const operationLogs = ref<OperationLog[]>([]);

// 计算属性
const testItem = computed(() => props.testItem);

// 方法
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    pending: 'orange',
    processing: 'blue',
    completed: 'green',
    error: 'red',
  };
  return colorMap[status] || 'default';
};

const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    pending: '待检验',
    processing: '检验中',
    completed: '已完成',
    error: '异常',
  };
  return textMap[status] || status;
};

const getDeviceStatusColor = () => {
  // 模拟设备状态
  return Math.random() > 0.3 ? 'green' : 'red';
};

const getDeviceStatusText = () => {
  return Math.random() > 0.3 ? '在线' : '离线';
};

const isDeviceOnline = () => {
  return Math.random() > 0.3;
};

const connectDevice = () => {
  message.success('设备连接成功');
  // 模拟连接过程
  setTimeout(() => {
    if (testItem.value) {
      testItem.value.status = 'processing';
      startProgress();
    }
  }, 1000);
};

const refreshStatus = () => {
  message.success('状态已刷新');
  // 模拟刷新状态
  if (testItem.value && testItem.value.status === 'processing') {
    updateProgress();
  }
};

const startProgress = () => {
  progressPercent.value = 0;
  progressStatus.value = 'active';
  progressColor.value = '#1890ff';

  // 添加初始状态消息
  statusMessages.value = [
    {
      time: dayjs().format('HH:mm:ss'),
      text: '开始检验流程',
      type: 'info',
    },
  ];

  // 模拟进度更新
  const interval = setInterval(() => {
    progressPercent.value += Math.random() * 20;

    if (progressPercent.value >= 100) {
      progressPercent.value = 100;
      progressStatus.value = 'success';
      progressColor.value = '#52c41a';

      // 添加完成消息
      statusMessages.value.push({
        time: dayjs().format('HH:mm:ss'),
        text: '检验完成',
        type: 'success',
      });

      // 更新检验项目状态
      if (testItem.value) {
        testItem.value.status = 'completed';
        testItem.value.completeTime = dayjs().format('YYYY-MM-DD HH:mm:ss');

        // 模拟生成结果
        if (testItem.value.name === '血常规') {
          testItem.value.result = '正常';
          testItem.value.abnormal = false;
        } else if (testItem.value.name === '血糖') {
          testItem.value.result = '5.2';
          testItem.value.unit = 'mmol/L';
          testItem.value.reference = '3.9-6.1';
          testItem.value.abnormal = false;
        }
      }

      clearInterval(interval);
    } else {
      // 添加进度消息
      const messages = [
        '正在准备样本...',
        '样本已加载到设备',
        '正在进行检验分析...',
        '检验数据计算中...',
        '生成检验报告...',
      ];

      const randomMessage =
        messages[Math.floor(Math.random() * messages.length)];
      statusMessages.value.push({
        time: dayjs().format('HH:mm:ss'),
        text: randomMessage,
        type: 'info',
      });
    }
  }, 2000);
};

const updateProgress = () => {
  // 模拟进度更新
  if (progressPercent.value < 100) {
    progressPercent.value += Math.random() * 10;

    statusMessages.value.push({
      time: dayjs().format('HH:mm:ss'),
      text: '状态更新',
      type: 'info',
    });
  }
};

const handleCancel = () => {
  emit('update:visible', false);
};

// 监听检验项目变化
watch(
  () => props.testItem,
  (newItem) => {
    if (newItem) {
      // 初始化操作记录
      operationLogs.value = [
        {
          time: newItem.createTime,
          action: '创建检验项目',
          operator: '李医生',
        },
        {
          time: dayjs().subtract(30, 'minute').format('YYYY-MM-DD HH:mm:ss'),
          action: '样本采集',
          operator: '张护士',
        },
        {
          time: dayjs().subtract(20, 'minute').format('YYYY-MM-DD HH:mm:ss'),
          action: '样本送检',
          operator: '王技师',
        },
      ];

      // 如果正在处理中，开始进度模拟
      if (newItem.status === 'processing') {
        startProgress();
      }
    }
  },
  { immediate: true },
);
</script>

<template>
  <a-modal
    :visible="visible"
    title="检验详情"
    width="800px"
    @cancel="handleCancel"
    :footer="null"
  >
    <div v-if="testItem" class="test-detail-modal">
      <!-- 基本信息 -->
      <div class="info-section">
        <h3>基本信息</h3>
        <div class="info-grid">
          <div class="info-item">
            <span class="label">检验项目：</span>
            <span class="value">{{ testItem.name }}</span>
          </div>
          <div class="info-item">
            <span class="label">检验设备：</span>
            <span class="value">{{ testItem.device }}</span>
          </div>
          <div class="info-item">
            <span class="label">检验状态：</span>
            <span class="value">
              <a-tag :color="getStatusColor(testItem.status)">
                {{ getStatusText(testItem.status) }}
              </a-tag>
            </span>
          </div>
          <div class="info-item">
            <span class="label">创建时间：</span>
            <span class="value">{{ testItem.createTime }}</span>
          </div>
          <div v-if="testItem.completeTime" class="info-item">
            <span class="label">完成时间：</span>
            <span class="value">{{ testItem.completeTime }}</span>
          </div>
        </div>
      </div>

      <!-- 检验结果 -->
      <div v-if="testItem.status === 'completed'" class="result-section">
        <h3>检验结果</h3>
        <div class="result-content">
          <div class="result-item">
            <span class="label">检验结果：</span>
            <span class="value" :class="{ abnormal: testItem.abnormal }">
              {{ testItem.result }}
              <span v-if="testItem.unit" class="unit">{{ testItem.unit }}</span>
            </span>
          </div>
          <div v-if="testItem.reference" class="result-item">
            <span class="label">参考范围：</span>
            <span class="value">{{ testItem.reference }}</span>
          </div>
          <div class="result-item">
            <span class="label">结果状态：</span>
            <span class="value">
              <a-tag :color="testItem.abnormal ? 'red' : 'green'">
                {{ testItem.abnormal ? '异常' : '正常' }}
              </a-tag>
            </span>
          </div>
        </div>
      </div>

      <!-- 设备状态 -->
      <div class="device-section">
        <h3>设备状态</h3>
        <div class="device-status">
          <div class="device-info">
            <div class="device-icon">🔬</div>
            <div class="device-details">
              <div class="device-name">{{ testItem.device }}</div>
              <div class="device-status-text">
                <a-tag :color="getDeviceStatusColor()">
                  {{ getDeviceStatusText() }}
                </a-tag>
              </div>
            </div>
          </div>
          <div class="device-actions">
            <a-button
              type="primary"
              size="small"
              @click="connectDevice"
              :disabled="!isDeviceOnline()"
            >
              连接设备
            </a-button>
            <a-button type="default" size="small" @click="refreshStatus">
              刷新状态
            </a-button>
          </div>
        </div>
      </div>

      <!-- 实时监控 -->
      <div v-if="testItem.status === 'processing'" class="monitor-section">
        <h3>实时监控</h3>
        <div class="monitor-content">
          <div class="progress-info">
            <div class="progress-text">检验进度</div>
            <a-progress
              :percent="progressPercent"
              :status="progressStatus"
              :stroke-color="progressColor"
            />
          </div>
          <div class="status-messages">
            <div
              v-for="(message, index) in statusMessages"
              :key="index"
              class="status-message"
              :class="message.type"
            >
              <span class="message-time">{{ message.time }}</span>
              <span class="message-text">{{ message.text }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作记录 -->
      <div class="log-section">
        <h3>操作记录</h3>
        <div class="log-list">
          <div
            v-for="(log, index) in operationLogs"
            :key="index"
            class="log-item"
          >
            <span class="log-time">{{ log.time }}</span>
            <span class="log-action">{{ log.action }}</span>
            <span class="log-operator">{{ log.operator }}</span>
          </div>
        </div>
      </div>
    </div>

    <div v-else class="empty-state">
      <div class="empty-icon">🔬</div>
      <div class="empty-text">未选择检验项目</div>
    </div>
  </a-modal>
</template>

<style scoped>
.test-detail-modal {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.info-section,
.result-section,
.device-section,
.monitor-section,
.log-section {
  padding: 16px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
}

.info-section h3,
.result-section h3,
.device-section h3,
.monitor-section h3,
.log-section h3 {
  margin: 0 0 16px;
  font-size: 16px;
  color: #333;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-item .label {
  width: 100px;
  font-size: 14px;
  color: #666;
}

.info-item .value {
  flex: 1;
  font-weight: bold;
  color: #333;
}

.result-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.result-item {
  display: flex;
  align-items: center;
}

.result-item .label {
  width: 100px;
  font-size: 14px;
  color: #666;
}

.result-item .value {
  flex: 1;
  font-weight: bold;
  color: #333;
}

.result-item .value.abnormal {
  color: #ff4d4f;
}

.result-item .unit {
  margin-left: 4px;
  font-weight: normal;
  color: #666;
}

.device-status {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.device-info {
  display: flex;
  align-items: center;
}

.device-icon {
  margin-right: 16px;
  font-size: 32px;
}

.device-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.device-name {
  font-weight: bold;
  color: #333;
}

.device-actions {
  display: flex;
  gap: 8px;
}

.monitor-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.progress-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.progress-text {
  font-weight: bold;
  color: #333;
}

.status-messages {
  max-height: 200px;
  padding: 12px;
  overflow-y: auto;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
}

.status-message {
  display: flex;
  gap: 12px;
  align-items: center;
  padding: 4px 0;
  font-size: 12px;
}

.status-message.info {
  color: #1890ff;
}

.status-message.success {
  color: #52c41a;
}

.status-message.warning {
  color: #faad14;
}

.status-message.error {
  color: #ff4d4f;
}

.message-time {
  min-width: 60px;
  color: #999;
}

.log-list {
  max-height: 200px;
  overflow-y: auto;
}

.log-item {
  display: flex;
  gap: 16px;
  align-items: center;
  padding: 8px 0;
  font-size: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.log-time {
  min-width: 120px;
  color: #999;
}

.log-action {
  flex: 1;
  color: #333;
}

.log-operator {
  min-width: 60px;
  color: #666;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #999;
}

.empty-icon {
  margin-bottom: 16px;
  font-size: 48px;
}

.empty-text {
  font-size: 14px;
}
</style>
